package com.xindaoapp.happypet.fragments;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alipay.android.app.sdk.AliPay;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.xindao.photonics.fragments.manager.BaseFragment;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.MyOrderListActivity;
import com.xindaoapp.happypet.activity.WebPayActivity;
import com.xindaoapp.happypet.alipy.Keys;
import com.xindaoapp.happypet.alipy.Result;
import com.xindaoapp.happypet.alipy.Rsa;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.CheckOrder;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;

/**
 * 尾巴圈收银台
 * 
 * @author chenghao
 * 
 */
public class CheckstandFragment extends BaseFragment {
    private final String TAG = "CheckstandFragment";
    private ImageView mImgClient;
    private ImageView mImgWeb;
    private String orderNumber;
    private float orderPrice;
    private Context mContext;
    private String orderTitle;

    private static final int RQF_PAY = 1;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Result result = new Result((String) msg.obj);
            switch (msg.what) {
                case RQF_PAY:// 支付成功
                    if (result.getResult().equals("9000")) {
                        Toast.makeText(getActivity(), "支付成功", Toast.LENGTH_SHORT).show();
                        Intent my_order = new Intent(getActivity(), MyOrderListActivity.class);
                        my_order.putExtra("submitOrder", true);
                        startActivity(my_order);
                    } else {
                        Builder dialog = new AlertDialog.Builder(mContext);
                        dialog.setMessage("支付失败,请重新支付!");
                        dialog.show();
                    }
                    break;
                default:
                    break;
            }
        };
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.layout_checkstand, container, false);
    }

    @Override
    protected void initEvents() {
        super.initEvents();
        getView().findViewById(R.id.clearing).setOnClickListener(mOnClickListener);
        getView().findViewById(R.id.r_client).setOnClickListener(mOnClickListener);
        getView().findViewById(R.id.r_web).setOnClickListener(mOnClickListener);
        mContext = getActivity();
    }

    private final OnClickListener mOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.clearing:// 去支付
                    if (!mImgClient.isSelected() && !mImgWeb.isSelected()) {
                        Toast.makeText(mContext, "请选择支付方式", Toast.LENGTH_SHORT).show();
                    }
                    GetOrderStatus();
                    break;
                case R.id.r_client:
                    if (!mImgClient.isSelected()) {
                        mImgClient.setSelected(true);
                        mImgWeb.setSelected(false);
                    }
                    break;
                case R.id.r_web:
                    if (!mImgWeb.isSelected()) {
                        mImgClient.setSelected(false);
                        mImgWeb.setSelected(true);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    private void GetOrderStatus() {
        RequestParams params = new RequestParams();
        params.put("order_sn", orderNumber);
        AddClient.get(Address.CHECKORDER, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                try {
                    CheckOrder order = JSON.parseObject(content, CheckOrder.class);
                    if (order.getStatus().equals("1")) {
                        if (mImgClient.isSelected()) {// 支付宝客户端
                            // TODO
                            String info = getNewOrderInfo();
                            String sign = Rsa.sign(info, Keys.PRIVATE);
                            sign = URLEncoder.encode(sign);
                            info += "&sign=\"" + sign + "\"&" + getSignType();
                            Log.i("ExternalPartner", "start pay");
                            // start the pay.
                            Log.i(TAG, "info = " + info);

                            final String orderInfo = info;
                            new Thread() {
                                @Override
                                public void run() {
                                    AliPay alipay = new AliPay(getActivity(), mHandler);

                                    String result = alipay.pay(orderInfo);

                                    Log.i(TAG, "result = " + result);
                                    Message msg = new Message();
                                    msg.what = RQF_PAY;
                                    msg.obj = result;
                                    mHandler.sendMessage(msg);
                                }
                            }.start();
                        } else if (mImgWeb.isSelected()) {// 支付宝web
                            Intent intent = new Intent(mContext, WebPayActivity.class);
                            Log.e("111", orderNumber);
                            intent.putExtra("orderId", orderNumber);
                            intent.putExtra("orderName", orderTitle);
                            intent.putExtra("orderPrice", orderPrice);// orderPrice
                            startActivity(intent);
                        }
                    }
                    if (order.getStatus().equals("0")) {
                        Toast.makeText(mContext, order.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                }
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error) {
                super.onFailure(error);
            }
        });
    }

    private String getNewOrderInfo() {
        StringBuilder sb = new StringBuilder();
        sb.append("partner=\"");
        sb.append(Keys.DEFAULT_PARTNER);
        sb.append("\"&out_trade_no=\"");
        sb.append(orderNumber);
        // sb.append(getOutTradeNo());
        sb.append("\"&subject=\"");// 订单标题
        sb.append(orderTitle);
        sb.append("\"&body=\"");// 订单内容
        sb.append(orderTitle);
        sb.append("\"&total_fee=\"");// 订单价格
        sb.append(orderPrice);// orderPrice
        sb.append("\"&notify_url=\"");

        // 网址需要做URL编码
        sb.append(URLEncoder
                .encode("http://ts.leepet.com/plugins/API.v1.0/?&a=order&m=notify&code=alipay"));
        // sb.append("http://ts.leepet.com/plugins/API.v1.0/?&a=order&m=notify&code=alipay");
        sb.append("\"&service=\"mobile.securitypay.pay");
        sb.append("\"&_input_charset=\"UTF-8");
        sb.append("\"&return_url=\"");
        sb.append(URLEncoder.encode("http://m.alipay.com"));
        sb.append("\"&payment_type=\"1");
        sb.append("\"&seller_id=\"");
        sb.append(Keys.DEFAULT_SELLER);

        // 如果show_url值为空，可不传
        // sb.append("\"&show_url=\"");
        sb.append("\"&it_b_pay=\"1m");
        sb.append("\"");
        return new String(sb);
    }

    private String getOutTradeNo() {
        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss");
        Date date = new Date();
        String key = format.format(date);

        java.util.Random r = new java.util.Random();
        key += r.nextInt();
        key = key.substring(0, 15);
        Log.d(TAG, "outTradeNo: " + key);
        return key;
    }

    private String getSignType() {
        return "sign_type=\"RSA\"";
    }

    @Override
    protected void initViews(View view) {
        super.initViews(view);
        mImgClient = (ImageView) view.findViewById(R.id.rb_client);
        mImgWeb = (ImageView) view.findViewById(R.id.rb_web);
        orderNumber = getArguments().getString(Constants.KEY_ORDER_NUMBER);
        orderPrice = getArguments().getFloat(Constants.KEY_ORDER_TOTAL_PRICE);
        orderTitle = getArguments().getString(Constants.KEY_ORDER_TITLE);
        ((TextView) view.findViewById(R.id.order_number)).setText(orderNumber);
        ((TextView) view.findViewById(R.id.order_price)).setText("￥"
                + CommonUtil.transitionToFloat(orderPrice));
        mImgClient.setSelected(true);
        mImgWeb.setSelected(false);
    }

    @Override
    protected String getTitleName() {
        return "尾巴圈收银台";
    }

    @Override
    protected boolean showRightView() {
        return false;
    }

}
